package com.spring.sperapc.web.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.spera.genutil.SpUtil;
import com.spera.genutil.TokenUtil;
import com.spring.security.core.context.JedisCont;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.iputil.HttpClientUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.dao.UserMapper;
import com.spring.security.web.model.User;
import com.spring.sperapc.web.dao.FamilyMemberMapper;
import com.spring.sperapc.web.dao.TracelogboMapper;
import com.spring.sperapc.web.dao.UserCommonMapper;
import com.spring.sperapc.web.model.FamilyMember;
import com.spring.sperapc.web.model.TracelogboWithBLOBs;
import com.spring.sperapc.web.service.UserCommonService;
import com.spring.tools.MyTools;

@Service
public class UserCommonServiceImpl implements UserCommonService{
    @Resource
    private UserCommonMapper userCommonMapper;
    
    @Resource
    private FamilyMemberMapper familyMemberMapper;
    
	@Resource
	private UserMapper userMapper;
    
	@Resource
	private JedisCache jedisCache;
	
	@Resource
	private TracelogboMapper tracelogboMapper;
    
    @Override
    public String getFamilyRoleCount(FamilyMember record) {
		String c_role_id = record.getcRoleId();
		String c_family_id = record.getcFamilyId();

		HashMap<String,Object> hm = new HashMap<String,Object>();
		hm.put("c_role_id", c_role_id);
		hm.put("c_family_id", c_family_id);
		if(c_role_id!=null&&c_family_id!=null){
		if (c_role_id.equals("1") || c_role_id.equals("2")) {
			int count = userCommonMapper.getFamilyRoleCount(hm);
			if (count >= 1) {
				return "0";
			}
		}}
		return "1";

    }
    
    
    @Override
    public String getFamilyRoleCountByID(FamilyMember record) {
		String c_role_id = record.getcRoleId();
		String c_user_id = record.getC_user_id();

		HashMap<String,Object> hm = new HashMap<String,Object>();
		hm.put("c_role_id", c_role_id);
		hm.put("c_user_id", c_user_id);
		hm.put("c_family_id", record.getcFamilyId());
		
		if(c_role_id!=null&&c_user_id!=null){
		if (c_role_id.equals("1") || c_role_id.equals("2")) {
			int count = userCommonMapper.getFamilyRoleCountByID(hm);
			if (count >= 1) {
				return "0";
			}
		}
		}
		return "1";

    }
    
    /**
     * 激活账号
     */
	@SuppressWarnings("rawtypes")
	@Override
	public Map<String, Object> enableUser(String token, String c_user_id, String phone, 
			String password,String val_num,String needValNum,HttpServletRequest request) throws Exception {
		Map<String, Object> m = new HashMap<String,Object>();
		Map<String, Object> t = TokenUtil.checkToken(token, jedisCache);
		if (t != null) {
			return t;
		}
		
		User s = new User();
		if (ApplicationUtils.isNotNull(phone)) {

			if (SpUtil.validatePhone(phone)) {
				s.setUsername(phone);
				s.setPhone(phone);
			}else {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入正确的手机号");
				return m;
			}
		} else {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入手机号");
			return m;
		}
		
		/**
		 * 需要验证码字段为空时，需要短信验证，不为空时，如果为9，则是后台教师激活，其余为失败
		 */
		/*if(!ApplicationUtils.isNotNull(needValNum)){
			if (!ApplicationUtils.isNotNull(val_num)) {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入短信验证码");
				return m;
			}
		}else if(!"9".equalsIgnoreCase(needValNum)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "激活参数有误，请重新操作");
			return m;
		}
		
		List<User> list = userMapper.selectByWhereStr(s);
		if ((ApplicationUtils.isNotNull(list)) && (list.size() > 0)) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "用户已存在");
			return m;
		}
		
		List<User> listp = userMapper.selectByPhone(s);
		if ((ApplicationUtils.isNotNull(listp)) && (listp.size() > 0)) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "手机号已被注册");
			return m;
		}
		
		if(!jedisCache.exists(phone)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "验证码已过期，请重新发送");
			return m;
		}
		
		String val_num_j = jedisCache.get(phone);
		if(!val_num.equals(val_num_j)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "验证码不正确");
			return m;
		}*/
		

		HashMap<String,Object> hmc = MyTools.checkIsNotNull(c_user_id);
		if (hmc != null) {
			return hmc;
		}
		//HashMap hm = MyTools.pageIndexToSkip(page_size, page_index, skip, rows);
		HashMap<String,Object> hm=new HashMap<String,Object>();
		hm.put("c_user_id", c_user_id);
		hm.put("phone", phone);
		hm.put("password", password);
		
		//List<FamilyMember> oldfamilyMembers=familyMemberMapper.selectByFamilyId(hm);
		///FamilyMember oldfamilyMember=oldfamilyMembers.get(0);

		int effect = userCommonMapper.enableUser(hm);
		
		if(effect!=1){

			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "启用失败");
			return m;
		}
		String myUserID=jedisCache.hget(token, TokenUtil.USER_ID);
		
		//修改业务的数据库手机号
		if(phone!=null&&!phone.equals("")){
	    	HashMap<String,Object> param=new HashMap<String,Object>();        	
	    	param.put("newPhone", phone);
	    	param.put("c_user_id", c_user_id);
			String returnString = HttpClientUtils.httpPost(JedisCont.getProParm("SperaChildrenPark")+"/SperaChildrenPark/spera/common/updatePhone",param);        	
			System.out.println(returnString);
		}
		
		TracelogboWithBLOBs tl = MyTools.getLog(jedisCache, token, request);
		tl.setEntitytypename("c_family_member");
		tl.setEntityid(c_user_id);
		tl.setLogcategory(2);
		tl.setLogdescription(MyTools.getChangeByMap(hm,"修改"));
		int effect2=tracelogboMapper.insert(tl);
		System.out.println(effect2);
		
		if(myUserID.equals(c_user_id)){
			jedisCache.del(token);

/*			Set set = jedisCache.hkeys("*");
			Iterator it = set.iterator();
	
			while (it.hasNext()) {
				String key = (String) it.next();
				String value = jedisCache.hget("key", phone);
				if(value!=null&&value.equals(oldfamilyMember.getPhone())){
					jedisCache.del(key);
					System.out.println("删除了token"+value);
				}
			}*/
		}
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "启用成功");
		return m;
	}
	
		
}
